import React from 'react'
import { connect } from 'dva'
import { DatePicker } from 'antd'
import moment from 'moment'
const { RangePicker } = DatePicker
const dateFormat = 'YYYY-MM-DD'


/**
 * [TimeRangeSelect 时间段选择]
 */
class TimeRangeSelect extends React.Component {

  state = {
    begindate: this.props.begindate,
    enddate: this.props.enddate,
  }

  componentWillReceiveProps(nextProps) {
    if((nextProps.begindate!=this.props.begindate)||(nextProps.enddate!=this.props.enddate)){
      this.setState({
        begindate: nextProps.begindate,
        enddate: nextProps.enddate,
      })
    }
  }

  handleChangeRangePicker = (date, dateString) => {
    //  更新组件state
    this.setState({
      begindate: dateString[0],
      enddate: dateString[1],
      timeRange:'0'
    })
    //  保存查询参数到URL
    this.changeRouter(dateString[0], dateString[1],'0')
  }

  changeRouter(beginVal, endVal) {
    //  保存查询参数到URL
    const { pathname, query } = this.props.location
    const payload={}
    payload.pathname=pathname
    payload.query=query
    payload.query[this.props.begindateName]=beginVal
    payload.query[this.props.enddateName]=endVal
    this.props.dispatch({
      type: `app/changeRouter`,
      payload
    })
  }
  render() {

    const { begindate, enddate } = this.state
    const { firstdate, lastdate } = this.props

    return (
      <RangePicker
          allowClear={false}
          value={begindate?[moment(begindate, dateFormat), moment(enddate, dateFormat)]:false}
          disabledDate={current => lastdate?((current < moment(firstdate, dateFormat)) || (current > moment(lastdate, dateFormat))):false}
          format={dateFormat}
          onChange={this.handleChangeRangePicker.bind(this)}
          style={{ width: 240,marginRight:10 }}
          className="timeRangeSelect"
        />
    )
  }
}
TimeRangeSelect.defaultProps = {
  begindate: null,
  enddate: null,
  firstdate: null, 
  lastdate: null, 
  begindateName:'begindate',
  enddateName:'enddate',
  location:{
    pathname:'/',
    query:{},
  }
}
export default connect()(TimeRangeSelect)
